package com.feizhaiyou.encrypt.codec;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.feizhaiyou.encrypt.constants.SecurityMode;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * AES的默认模式是：AES/ECB/PKCS5Padding
 *
 * @author ls
 */
@Data
@Slf4j
public class AESProcessor implements SecurityProcessor {

    private String secret;

    private AES aes;

    public AESProcessor(String secret) {
        if (StringUtils.isBlank(secret)) {
            secret = generateKey();
            log.warn("AESProcessor is not configured with a secret, use randomly generated secret: {}", secret);
        }
        this.secret = secret;
        this.aes = SecureUtil.aes(SecureUtil.decode(secret));
    }

    @Override
    public byte[] decrypt(String text) {
        return aes.decrypt(text);
    }

    @Override
    public byte[] encrypt(byte[] data) {
        return aes.encrypt(data);
    }

    /**
     * 以base64编码生成AES秘钥
     *
     * @return
     */
    public static String generateKey() {
        return generateKey(SecurityMode.BASE64);
    }

    /**
     * 生成AES秘钥
     *
     * @param type {@link SecurityMode} 编码模式
     * @return
     */
    public static String generateKey(SecurityMode type) {
        byte[] keyBytes = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        switch (type) {
            case HEX:
                return HexUtil.encodeHexStr(keyBytes);
            case BASE64:
            default:
                return Base64Encoder.encode(keyBytes);
        }
    }

    public static void main(String[] args) {
        //随机生成密钥
//        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        String secret = generateKey();
        System.out.println(secret);
        AESProcessor processor = new AESProcessor(null);
        byte[] encrypt = processor.encrypt("Java".getBytes());
        String encode1 = Base64Encoder.encode(encrypt);
        System.out.println(encode1);
        byte[] decrypt = processor.decrypt(encode1);
        System.out.println(StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8));
    }
}
